package com.dhcc.bpm.common.redisMessage;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName RedisMessageSender
 * @Description 发布订阅模式发送器
 * @Author xiafayu
 * @Date 2020/2/21 0021 15:16
 * @Version V1.0
 * @Copyright: 2020 东华软件 . All rights reserved.
 **/
@Component
public class RedisMessageSender {
	private static final Logger log = LoggerFactory.getLogger(RedisMessageSender.class);
	private static final String CHANNEL = "MANAGER";
	private static final String GATEWAY = "GATEWAY";

	@Autowired
	private StringRedisTemplate stringRedisTemplate;

	/**
	 * @Description: 消息发送(订阅端发送)
	 * @param message
	 */
	public void sendMessageToManager(String message) {
		log.info("发送通知：" + message);
		stringRedisTemplate.convertAndSend(CHANNEL, message);
	}

	/**
	 * @Description: 消息发送(发布端发送)
	 * @param gatewayCode  网关编码
	 * @param message  格式  config_+网关编号
	 */
	public void sendMessageToGateway( String gatewayCode,String message) {
		log.info("发送通知：gatewayCode [{}],message[{}]", gatewayCode, message);
		if(gatewayCode != null && !"".equals(gatewayCode)){
			stringRedisTemplate.convertAndSend(GATEWAY + ":" + gatewayCode, message);
		}else{
			stringRedisTemplate.convertAndSend(GATEWAY, message);
		}
	}

	/**
	 * @Description: 消息发送(发布端发送)
	 * @param channel  token
	 * @param message  格式  config_+网关编号
	 */
	public void sendMessageToChannel( String channel,String message) {
		log.info("发送通知：channel [{}],message[{}]", channel, message);
		stringRedisTemplate.convertAndSend(channel, message);
	}

	/**
	 * @Description: 消息格式化
	 *
	 * @param configname
	 *            配置名称
	 * @param message
	 *            消息内容
	 * @return
	 */
	public static String format(String configname, String message) {
		return  configname + "_" + message;
	}


	/**
	 * @Description 消息生产者
	 * @Author xiafayu
	 * @Date 2020/4/28 14:16
	 * @param key
	 * @param obj
	 * @return boolean
	 * @throws
	 **/
	public boolean produceMessage(String key,Object obj){
		try {
			stringRedisTemplate.opsForList().leftPush(key, obj.toString());
			return true;
		} catch (Exception e) {
			log.error("redis异常：{}", e);
			return false;
		}
	}

	/**
	 * @Description 消息生产者
	 * @Author xiafayu
	 * @Date 2020/4/28 14:16
	 * @param key
	 * @return boolean
	 * @throws
	 **/
	public Object consumeMessage(String key){
		try {
			Object obj = null;
			if(stringRedisTemplate.opsForList().size(key) > 0){
				obj = stringRedisTemplate.opsForList().rightPop(key, -1 , TimeUnit.MILLISECONDS);
			}

			return obj;
		} catch (Exception e) {
			log.error("redis异常：{}", e);
			return null;
		}
	}
}
